package cn.wolfcode.shop.cloud.web.controller;

import cn.wolfcode.shop.cloud.annotation.UserParam;
import cn.wolfcode.shop.cloud.common.BusinessException;
import cn.wolfcode.shop.cloud.common.Result;
import cn.wolfcode.shop.cloud.domain.OrderInfo;
import cn.wolfcode.shop.cloud.domain.SeckillOrder;
import cn.wolfcode.shop.cloud.domain.User;
import cn.wolfcode.shop.cloud.mq.MQConstans;
import cn.wolfcode.shop.cloud.mq.OrderMessage;
import cn.wolfcode.shop.cloud.msg.SeckillGoodCodeMsg;
import cn.wolfcode.shop.cloud.service.IOrderInfoService;
import cn.wolfcode.shop.cloud.service.ISeckillGoodService;
import cn.wolfcode.shop.cloud.service.ISeckillOrderService;
import cn.wolfcode.shop.cloud.service.RedisService;
import cn.wolfcode.shop.cloud.util.SeckillKeyPrefix;
import cn.wolfcode.shop.cloud.vo.SeckillGoodVO;
import org.apache.catalina.connector.Response;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class SeckillOrderInfoController {
    @Autowired
    private ISeckillGoodService seckillGoodService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    public static final ConcurrentHashMap<Long, Boolean> map = new ConcurrentHashMap<>();

    @RequestMapping("{path}/doSeckill")
    public Result doSeckill(@UserParam User user, Long seckillId, String uuid, @PathVariable String path,String verifyCode) {
        //参数校
        // 1判断是否登录,如果用户未登录提醒用户违法操作
        if (user == null) {
            throw new BusinessException(SeckillGoodCodeMsg.NOT_LOGIN);
        }
        String paths = redisService.get(SeckillKeyPrefix.REDIS_SECKILL_PATH, uuid, String.class);
        if (StringUtils.isEmpty(path) || !paths.equals(path)) {
            throw new BusinessException(SeckillGoodCodeMsg.ORDER_PATH_ERROR);
        }
         Integer ret = redisService.get(SeckillKeyPrefix.VERIFYCODE_RESULT, uuid, Integer.class);
        System.out.println(verifyCode);
        if (StringUtils.isEmpty(verifyCode)){
            throw new BusinessException(SeckillGoodCodeMsg.NO_VERIFYCODE);
        }
        if (!verifyCode.equals(ret+"")){
            throw new BusinessException(SeckillGoodCodeMsg.VERIFYCODE_ERROR);
        }

        Boolean flag = SeckillOrderInfoController.map.get(seckillId);

        if (flag != null && flag) {
            //没有库存了
            throw new BusinessException(SeckillGoodCodeMsg.NO_STOCKCOUNT);
        }

//2根据秒杀商品的id,上数据库去查询有没有数据,如果没有提醒违法操作
        SeckillGoodVO seckillGoodVO = seckillGoodService.queryByIdByRedis(seckillId);
        if (seckillGoodVO == null) {
            throw new BusinessException(SeckillGoodCodeMsg.VIOLATION_OPERATION);
        }
//3判断商品的秒杀时间是否开始,如果未开始或者是已经结束了,提醒用户违法操作
        Date now = new Date();
        if (seckillGoodVO.getStartDate().getTime() > now.getTime() ||
                seckillGoodVO.getEndDate().getTime() < now.getTime()) {
            throw new BusinessException(SeckillGoodCodeMsg.VIOLATION_OPERATION);
        }

//4判断用户是否重复下单,如果重复下单提醒请不要重复下单
        //到数据库里面查t_seckill_order表，有没有seckillOrder数据，有的话不能再下单
      /*  SeckillOrder seckillOrder =seckillOrderService.queryBySidAndUid(user.getId(),seckillId);
        if (seckillOrder!=null){
            throw new BusinessException(SeckillGoodCodeMsg.NOT_DOUBLE_ORDER);
        }*/
        //操作redis判断,redis里是否存在这个key，存在的话就算重复下单
        if (redisService.exists(SeckillKeyPrefix.REDIS_SECKILL_ORDER, user.getId() + ":" + seckillId)) {
            throw new BusinessException(SeckillGoodCodeMsg.NOT_DOUBLE_ORDER);
        }
//5判断是否有库存,如果没有提醒库存不足

       /* if (seckillGoodVO.getStockCount()<=0){ 从数据库里取库存
            throw new BusinessException(SeckillGoodCodeMsg.NO_STOCKCOUNT);
        }*/
        //从redis里减库存
        Long count = redisService.decr(SeckillKeyPrefix.SECKILL_STOCK_COUNT, seckillId + "");
        if (count < 0) {
            map.put(seckillId, true);
            throw new BusinessException(SeckillGoodCodeMsg.NO_STOCKCOUNT);
        }


//6 秒杀
        //调用服务去seckillId
        //String orderNo =orderInfoService.doSeckill(user.getId(),seckillId);
        //用消息中间件处理,/发送同步消息seckillId，userId；把参数封装到对象
        OrderMessage orderMessage = new OrderMessage();
        orderMessage.setUserId(user.getId());
        orderMessage.setSeckillId(seckillId);
        orderMessage.setUuid(uuid);
        //同步发送消息
        rocketMQTemplate.syncSend(MQConstans.CREATE_ORDER_DEST, orderMessage);


// 6.1减库存
// 6.2创建出来订单信息保存到数据库中
// 6.3往tseckilL_order去存储一条数据
        return Result.success("正在抢购中");
    }

    @RequestMapping("queryByorderNo")
    public Result queryByorderNo(String orderNo, @UserParam User user) {
        if (user == null) {
            throw new BusinessException(SeckillGoodCodeMsg.NOT_LOGIN);
        }
        OrderInfo orderInfo = orderInfoService.queryByorderNo(orderNo);
        //参数校验
        if (orderInfo == null) {
            throw new BusinessException(SeckillGoodCodeMsg.VIOLATION_OPERATION);
        }
        //用户只能看自己的订单信息
        if (!user.getId().equals(orderInfo.getUserId())) {
            throw new BusinessException(SeckillGoodCodeMsg.VIOLATION_OPERATION);
        }
        return Result.success(orderInfo);
    }
}
